#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;

    using namespace log_ns;
    const static int gbacklog = 8;

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int bakclog = gbacklog) = 0;
        virtual int Accepter(InetAddr *cliaddr) = 0;
        virtual bool Connecter(const std::string &peerip, const uint16_t peerport) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;

        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;
        virtual void ReUesAddr() = 0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            ReUesAddr(); 
            CreateBindOrDie(port);
            CreateListenOrDie();
        }
        bool BuildClientSocket(const std::string &peerip, const uint16_t peerport)
        {
            CreateSocketOrDie();
            return Connecter(peerip, peerport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {
        }
        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }
        ~TcpSocket()
        {
        }
        void CreateSocketOrDie() override
        {
            // 1.创建套接字
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create error!\n");
                exit(1);
            }
            LOG(INFO, "_sockfd create success, _sockfd: %d\n", _sockfd);
        }
        void CreateBindOrDie(uint16_t port) override
        {
            // 2.绑定
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;

            int m = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (m < 0)
            {
                LOG(FATAL, "bind error!\n");
                exit(2);
            }
            // LOG(INFO, "bind success!\n");
        }
        void CreateListenOrDie(int bakclog) override
        {
            // 3.设为监听状态  因为tcp是面向连接的，所以要不断的获取连接
            if (::listen(_sockfd, gbacklog) < 0)
            {
                LOG(FATAL, "listen error!\n");
                exit(3);
            }
            // LOG(INFO, "listen success!\n");
        }
        // 输出型参数，得到客户端的地址
        int Accepter(InetAddr *cliaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 4.获取新连接
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                // 获取失败了，不会退出，会下一次连接
                LOG(WARNING, "accept error!\n");
                return -1;
            }
            *cliaddr = InetAddr(client);
            LOG(INFO, "get a new link, client info: [%s], sockfd: %d\n", cliaddr->AddrStr().c_str(), sockfd);

            //return std::make_shared<TcpSocket>(sockfd);
            return sockfd;
        }
        // 需要传递远端的ip和端口号
        bool Connecter(const std::string &peerip, const uint16_t peerport) override
        {
            // 2.OS自动绑定  发起连接
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect socket error!" << std::endl;
                return false;
            }
            return true;
        }
        int Sockfd()
        {
            return _sockfd;
        }
        void Close()
        {
            if (_sockfd > 0)
                ::close(_sockfd);
        }

        ssize_t Recv(std::string *out) override
        {
            // 5.接收客户端发的信息
            char inbuffer[4096];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                // 读取成功
                inbuffer[n] = 0;
                *out += inbuffer; // 有人不断的从网络中发送过来，直接拼到后面
            }
            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }
        void ReUesAddr() override
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }

    private:
        int _sockfd; // 可以是listensock,普通socketfd
    };

    Socket *sock = new TcpSocket();
}